//
//  PeerFileServer.m
//  SimpleServer
//
//  Created by Sean Breid on 12/18/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "PeerFileServer.h"

@implementation PeerFileServer


-(id)initWithPort: (NSInteger) port{
    
    self = [super init];
    
    ServerSocket = [[TCP4Socket alloc] initWithPort:port];
    
    return self;
    
}

-(void)runServer{
    
    [NSThread detachNewThreadSelector:@selector(acceptClients:) toTarget:[PeerFileServer class] withObject:ServerSocket];
    
}

+(void)acceptClients: (id) serverSock{
    
    
    [serverSock Listen];

    
    while(true){
    
       TCP4Socket* clientSocket = [serverSock Accept];
        
        [NSThread detachNewThreadSelector:@selector(serveClient:) toTarget:[PeerFileServer class] withObject:clientSocket];
        
    }
    
}


+(void)serveClient: (id) clientSock{
 
    //NSData* sendBuffer = [@"Hello\n" dataUsingEncoding:NSUTF8StringEncoding];
    
    while(true){
        
        NSData* fileBuffer = [clientSock ReceiveBufferOfSize:1000];
            
        NSString* fileName = [[NSString alloc] initWithData:fileBuffer encoding:NSUTF8StringEncoding];
        
        if([fileName isEqualToString: @"exit"]){
            break;
        }
        
        //const char* buf = [fileName UTF8String];
        
        //fileName = [NSString stringWithUTF8String:buf];
        
        fileName = [NSString stringWithUTF8String:[fileName UTF8String]];

        
        NSString* path = @"/Users/brei0118/Desktop/ipad-p2p-project/";
        
        fileName = [path stringByAppendingString:fileName];
        
        NSError* fileError;
                
        NSData* sendBuffer = [NSData dataWithContentsOfFile:fileName options:nil error: &fileError];
        
        if(sendBuffer == nil){
            
            NSData* err = [@"File Not Found" dataUsingEncoding:NSUTF8StringEncoding];
            [clientSock SendWithBuffer:err ofSize:[err length]];
            
        }
        else{
            
            NSUInteger length = [sendBuffer length];
            NSUInteger chuckSize = 1000000;
            NSUInteger offset = 0;
            
            do{
                
                NSUInteger curChunkSize = length - offset > chuckSize ? chuckSize : length - offset;
                
                NSData* data = [NSData dataWithBytesNoCopy:(void*)[sendBuffer bytes] + offset length:curChunkSize freeWhenDone:NO];
                
                offset += curChunkSize;
                
                [clientSock SendWithBuffer:data ofSize: [data length]];
                
            }while(offset < length);
    
            
        }
        
    }
    
    [clientSock Close];
    
}



@end
